home *** CD-ROM | disk | FTP | other *** search
- ' The first version of the Person class demonstrates properties, methods, indexers,
- ' read-only, write-only, and default properties
-
- Class Person
- ' Visual Basic.NET classes can expose Public constants.
- Public Const DefaultPassword As String = "mypwd"
-
- ' Fields visible from outside the class
- Public FirstName As String
- Public LastName As String
-
- ' You can define up to four addresses for this person,
- ' from Address(0) to Address(3).
- Public Address(3) As String
-
- ' an overridable method
-
- Overridable Function CompleteName(Optional ByVal title As String = "") As String
- ' Use the title, if provided.
- If title <> "" Then CompleteName = title & " "
- ' Append first and last name.
- CompleteName &= FirstName & " " & LastName
- End Function
-
- ' the BirthDate property
-
- Dim m_BirthDate As Date
-
- Property BirthDate() As Date
- Get
- Return m_BirthDate
- End Get
- Set(ByVal Value As Date)
- m_BirthDate = Value
- End Set
- End Property
-
- ' the Spouse property
-
- Private m_Spouse As Person
-
- Property Spouse() As Person
- Get
- Return m_Spouse
- End Get
- Set(ByVal Value As Person)
- m_Spouse = Value
- End Set
- End Property
-
- ' The Age property is read-only.
-
- ReadOnly Property Age() As Integer
- Get
- Return Year(Now) - Year(m_BirthDate)
- End Get
- End Property
-
- ' LoginDate is a write-only property.
-
- Dim m_LoginDate As Date
-
- WriteOnly Property LoginDate() As Date
- Set(ByVal Value As Date)
- m_LoginDate = Value
- End Set
- End Property
-
- ' an example of indexer
-
- Dim m_Notes(10) As String
-
- ' The Attachment property takes an Integer argument.
- ' Note that this is also the default property.
-
- Default Property Notes(ByVal index As Integer) As String
- Get
- If index < 0 Or index > UBound(m_Notes) Then
- Throw New IndexOutOfRangeException("Invalid note index")
- End If
- Return m_Notes(index)
- End Get
- Set(ByVal Value As String)
- If index < 0 Or index > UBound(m_Notes) Then
- Throw New IndexOutOfRangeException("Invalid note index")
- End If
- m_Notes(index) = Value
- End Set
- End Property
-
- ' The GotMail event is used to demonstrate event inheritance
-
- Event GotMail(ByVal msgText As String)
-
- Sub NotifyNewMail(ByVal msgText As String)
- ' Let all listeners know that we got mail.
- RaiseEvent GotMail(msgText)
- End Sub
-
- ' The Father, Mother and AreBrothers method are used to demonstrate shared member inheritance
-
- Public Father As Person
- Public Mother As Person
-
- Shared Function AreBrothers(ByVal p1 As Person, ByVal p2 As Person) As Boolean
- Return (p1.Father Is p2.Father) Or (p1.Mother Is p2.Mother)
- End Function
- End Class
-
- ' This second version of the Person class demonstrates overloaded constructors,
- ' read-only fields, and the Finalize method.
-
- Class Person2
- ' a public read-only field that can be assigned only from inside the constructor.
- Public ReadOnly CreateTime As Date
-
- ' First version takes first and last name.
- Sub New(ByVal firstName As String, ByVal lastName As String)
- Me.FirstName = firstName
- Me.LastName = lastName
- ' Remember when this instance was created.
- CreateTime = Now()
- End Sub
-
- ' Second version takes complete name (e.g. "Joe Doe").
- Sub New(ByVal completeName As String)
- Dim i As Integer
- i = InStr(completeName, " ")
- ' Error if there are fewer than two words.
- If i = 0 Then Throw New ArgumentException("Invalid Name")
- ' Initialize main properties.
- Me.FirstName = RTrim(Left(completeName, i - 1))
- Me.LastName = LTrim(Mid(completeName, i + 1))
- ' Remember when this instance was created.
- CreateTime = Now()
- End Sub
-
-
- Private m_FirstName As String
- Private m_LastName As String
-
- Property FirstName() As String
- Get
- Return m_FirstName
- End Get
- Set(ByVal Value As String)
- If Value = "" Then
- Throw New ArgumentException("Invalid FirstName property")
- End If
- m_FirstName = Value
- End Set
- End Property
-
- Property LastName() As String
- Get
- Return m_LastName
- End Get
- Set(ByVal Value As String)
- If Value = "" Then
- Throw New ArgumentException("Invalid LastName property")
- End If
- m_LastName = Value
- End Set
- End Property
-
- ' the BirthDate property
-
- Dim m_BirthDate As Date
-
- Property BirthDate() As Date
- Get
- Return m_BirthDate
- End Get
- Set(ByVal Value As Date)
- m_BirthDate = Value
- End Set
- End Property
-
- Overridable Function CompleteName() As String
- ' Append first and last name.
- Return FirstName & " " & LastName
- End Function
-
- Protected Overrides Sub Finalize()
- ' NOTE: we output this message to the debug window (instead of the console)
- ' because if the Finalize method is called by the very last GC that fires
- ' when the application completes, then the Console object isn't available any longer.
- Debug.WriteLine("Person " & Me.CompleteName() & " is being destroyed")
- End Sub
-
- End Class
-
-
- ' The Person3 class demonstrates how to use the MyClass keyword and the problems
- ' you have when you omit it
-
- Enum Gender
- NotSpecified
- Male
- Female
- End Enum
-
- Class Person3
- ' (In a real-world class, these would be properties.)
- Public FirstName As String
- Public LastName As String
- Public Gender As Gender = Gender.NotSpecified
-
- ' the usual constructor
- Sub New(ByVal firstName As String, ByVal lastName As String)
- Me.FirstName = firstName
- Me.LastName = lastName
- End Sub
-
-
- Dim m_Title As String
- Overridable Property Title() As String
- Get
- Return m_Title
- End Get
- Set(ByVal Value As String)
- m_Title = Value
- End Set
- End Property
-
- ' Prefix the name with a title if one has been specified.
- Function TitledName() As String
- If Title <> "" Then
- Return Title & " " & FirstName & " " & LastName
- Else
- Return FirstName & " " & LastName
- End If
- End Function
-
- Public BirthDate As Date
-
- ' Age is defined as the number of whole years passed from BirthDate.
- Overridable ReadOnly Property Age() As Integer
- Get
- Age = CInt(DateDiff(DateInterval.Year, BirthDate, Now()))
- If Month(Now) < Month(BirthDate) Or _
- (Month(Now) = Month(BirthDate) And _
- Day(Now) < Day(BirthDate)) Then
- ' Correct if this year's birthday hasn't occurred yet.
- Age = Age - 1
- End If
- End Get
- End Property
-
- ' an incorrect version of the CanVote property
- ReadOnly Property CanVote() As Boolean
- Get
- ' This statement isn't correct.
- Return (Age >= 18)
- End Get
- End Property
-
- ' the correct version of the CanVote property
- ReadOnly Property CanVote2() As Boolean
- Get
- ' Ensure that it always uses the non-overridden
- ' version of the Age property.
- Return (MyClass.Age >= 18)
- End Get
- End Property
-
- ' an non-overridable Address property
- Dim m_Address As String
-
- Property Address() As String
- Get
- Return m_Address
- End Get
- Set(ByVal Value As String)
- m_Address = Value
- End Set
- End Property
-
- End Class
-
-
- ' The Widget class demonstrates the IDisposable interface.
- ' and performance of Overridable and NotOverridable methods.
-
- Class Widget
- Implements IDisposable
-
- Function GetInteger() As Integer
- Return 1
- End Function
-
- Overridable Function GetInteger2() As Integer
- Return 1
- End Function
-
- Sub Dispose() Implements IDisposable.Dispose
- ' Close files and release other resources here.
- ' ...
- End Sub
- End Class
-
-
- ' This version of the DataFile class uses the GC.SuppressFinalize method
- ' for optimized clean-up code.
-
- Class DataFile2
- Implements IDisposable
-
- ' The file handle
- Private handle As Integer
-
- ' Open a file, store its handle.
- Sub Open(ByVal inputFile As String)
- ' Throw an exception if the object has been already disposed.
- If disposed Then Throw New ObjectDisposedException("DataFile2")
- ' Continue with regular operations.
- handle = FreeFile()
- FileOpen(handle, inputFile, OpenMode.Input)
- End Sub
-
- ' Close the file, don't throw an exception if already closed.
- Sub Close()
- ' Throw an exception if the object has been already disposed.
- If disposed Then Throw New ObjectDisposedException("DataFile2")
- ' Continue with regular operations.
- If handle <> 0 Then
- FileClose(handle)
- handle = 0
- End If
- End Sub
-
- ' This private variable is True if the object has been disposed.
- Protected disposed As Boolean
-
- Sub Dispose() Implements IDisposable.Dispose
- Debug.WriteLine("Dispose method")
- ' Execute the code that does the clean up.
- Dispose(True)
- ' Let the CLR know that Finalize doesn't have to be called.
- GC.SuppressFinalize(Me)
- End Sub
-
- Protected Overrides Sub Finalize()
- Debug.WriteLine("Finalize method")
- ' Execute the code that does the clean up.
- Dispose(False)
- End Sub
-
- ' This procedure is where the actual cleanup occurs.
- Protected Overridable Sub Dispose(ByVal disposing As Boolean)
- ' Exit now if the object has been already disposed.
- If disposed Then Exit Sub
-
- If disposing Then
- ' The object is being disposed, not finalized.
- ' It is safe to access other objects (other than the base
- ' object) only from inside this block.
- End If
-
- ' Perform clean up chores that have to be executed in either case.
- Close()
-
- ' Remember that the object has been disposed.
- disposed = True
- End Sub
- End Class
-
- ' This class inherits from DataFile2 and overrides the Dispose and FInalize methods.
-
- Class BetterDataFile2
- Inherits DataFile2
-
- Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
- ' Exit now if the object has been already disposed.
- If disposed Then Exit Sub
-
- If disposing Then
- ' The object is being disposed, not finalized.
- ' It is safe to access other objects (other than the base
- ' object) only from inside this block.
- End If
-
- ' Perform clean up chores that have to be executed in either case.
- ' ...
-
- ' Call the base class's Dispose method
- MyBase.Dispose(disposing)
- End Sub
-
- End Class
-
- ' The Employee class demonstrate inheritance
-
- Class Employee
- Inherits Person
-
- ' Two new public fields
- Public BaseSalary As Single
- Public HoursWorked As Integer
- ' A new private field
- Private m_HourlySalary As Single
-
- ' A new property
- Property HourlySalary() As Single
- Get
- Return m_HourlySalary
- End Get
- Set(ByVal Value As Single)
- m_HourlySalary = Value
- End Set
- End Property
-
- ' A new method
- Function Salary() As Single
- Return BaseSalary + m_HourlySalary * HoursWorked
- End Function
-
- ' redefine the AreBrothers shared method
-
- Shared Shadows Function AreBrothers(ByVal e1 As Employee, _
- ByVal e2 As Employee) As Boolean
- Return Person.AreBrothers(e1, e2) And (e1.LastName = e2.LastName)
- End Function
-
- End Class
-
- ' The second version of the Employee class demonstrates constructors with arguments
-
- Class Employee2
- Inherits Person2
-
- Public Title As String ' A new field
-
- ' two overloaded constructors
-
- Sub New(ByVal firstName As String, ByVal lastName As String)
- ' The first executable statement *must* be a call
- ' to the constructor in the base class.
- MyBase.New(firstName, lastName)
- ' You can continue with the initialization step here.
- ' ...
- End Sub
-
- Sub New(ByVal firstName As String, ByVal lastName As String, ByVal title As String)
- ' The first executable statement *must* be a call
- ' to the constructor in the base class.
- MyBase.New(firstName, lastName)
- ' set the new field
- Me.Title = title
- End Sub
-
- Overrides Function CompleteName() As String
- If Title <> "" Then CompleteName = Title & " "
- CompleteName &= MyBase.CompleteName()
- End Function
- End Class
-
- Class Employee3
- Inherits Person3
-
- ' the usual constructor
- Sub New(ByVal firstName As String, ByVal lastName As String)
- MyBase.New(firstName, lastName)
- End Sub
-
- ' Always provide a title if one hasn't been assigned.
- Overrides Property Title() As String
- Get
- If MyBase.Title <> "" Then
- Return MyBase.Title
- ElseIf Gender = Gender.Male Then
- Return "Mr."
- ElseIf Gender = Gender.Female Then
- Return "Mrs."
- End If
- End Get
- Set(ByVal Value As String)
- MyBase.Title = Value
- End Set
- End Property
-
- ' Age is defined as difference between the current year
- ' and the year when the employee was born.
- Overrides ReadOnly Property Age() As Integer
- Get
- Age = CInt(DateDiff(DateInterval.Year, BirthDate, Now()))
- End Get
- End Property
-
- ' the Address property demonstrates that you can always "manually" override
- ' a procedure that is marked as non-overridable in the base class.
- Shadows Property Address() As String
- Get
- Return MyBase.Address
- End Get
- Set(ByVal Value As String)
- If Value = "" Then Throw New ArgumentException()
- MyBase.Address = Value
- End Set
- End Property
-
- End Class
-
- ' Shape virtual class defines a behavior for other classes
-
- MustInherit Class Shape
- ' Position on the X-Y plane
- Public X, Y As Single
-
- ' Move the object on the X-Y plane.
- Sub Offset(ByVal deltaX As Single, ByVal deltaY As Single)
- X = X + deltaX
- Y = Y + deltaY
- ' Redraw the shape at the new position.
- Display()
- End Sub
-
- ' A virtual method
- MustOverride Sub Display()
- End Class
-
- ' The Square class derives from Shape and also demonstrates how you can use
- ' private constructors
-
- Class Square
- Inherits Shape
-
- Public Side As Single
-
- Overrides Sub Display()
- ' add here the statements that draw a square
- End Sub
-
- ' This private constructor prevents clients from
- ' instancing this class directly.
- Private Sub New(ByVal side As Single)
- Me.Side = side
- End Sub
-
- ' Clients can create a square only through this shared method.
- Shared Function CreateSquare(ByVal side As Single) As Square
- Return New Square(side)
- End Function
-
- End Class
-
- ' The Animal and Peripheral classes demonstrate nested classes
-
- Class Animal
- ' ...
- ' This class can be referred to as Animal.Mouse.
- Class Mouse
- ' ...
- End Class
- End Class
-
- Class Peripheral
- Dim m As Mouse
- Dim kb As Keyboard
- Dim k As Keyboard.Key
-
- ' ...
- ' This class can be referred to as Peripheral.Mouse.
- Class Mouse
- Dim kb As Keyboard
- Dim k As Keyboard.Key
- ' ...
- End Class
-
- ' This class can be referred to as Peripheral.Keyboard.
- Class Keyboard
-
- ' A private member
- Dim m_Brand As String
-
- ' This shared member is True if this class supports
- ' non-Latin keyboards.
- Public Shared SupportsNonLatinKeyboards As Boolean
-
- ReadOnly Property Brand() As String
- Get
- ' Code inside the outer class can access a private
- ' member without any reference (Me is implicit).
- Return m_Brand
- End Get
- End Property
-
- ' This class can be referred to as Peripheral.Keyboard.Key.
- Class Key
-
- ' This public field is meant to be assigned when creating
- ' an instance of the Key class.
- Public ParentKeyboard As Keyboard
-
- ReadOnly Property Brand() As String
- Get
- ' Code inside the inner class can access a private member
- ' in the outer class, but requires an object reference.
- Return ParentKeyboard.m_Brand
- End Get
- End Property
-
- ReadOnly Property SupportsNonLatin() As Boolean
- Get
- ' You can access a shared member in the outer class
- ' without an object reference.
- Return SupportsNonLatinKeyboards
- End Get
- End Property
-
- End Class
- End Class
- End Class
-
- ' The Customer, GoodCustomer, and ForeignCustomer classes demonstrate scope concepts
-
- Class Customer
- ' This member is visible to this class and
- ' classes derived from this class.
- Protected AlwaysPaysOnTime As Boolean
-
- ' Compute the discount percentage on products.
- Protected Overridable Function ProductDiscount() As Single
- ' Offer an additional discount if the customer always pays on time.
- If AlwaysPaysOnTime Then
- ProductDiscount = 15
- Else
- ProductDiscount = 10
- End If
- End Function
-
- ' By default make no discount on shipment.
- Protected Overridable Function ShipmentDiscount() As Single
- Return 0
- End Function
-
- ' Compute the actual discount on an order, given the
- ' amount of products purchased and the amount of shipment.
- Function TotalOrderAmount(ByVal ProductAmount As Single, _
- ByVal ShipmentAmount As Single) As Single
- Return ProductAmount * (1 - ProductDiscount() / 100) _
- + ShipmentAmount * (1 - ShipmentDiscount() / 100)
- End Function
-
- ' a protected nested class
- Protected Class OrderHistory
- Public Count As Integer
- Public TotalAmount As Single
- ' ...
- End Class
-
- End Class
-
- Class GoodCustomer
- Inherits Customer
-
- Sub New()
- ' Note that no MyBase.New is needed, because the base
- ' class has no constructor with parameters.
- AlwaysPaysOnTime = True
- End Sub
-
- ' A derived class sees protected nested classes.
- Dim oh As Customer.OrderHistory
- ' Note that you don't even need the dot syntax.
- Dim oh2 As OrderHistory
-
- End Class
-
- Class ForeignCustomer
- Inherits Customer
-
- ' A convenient constructor that lets us test well- and
- ' ill-behaved foreign customers.
- Sub New(ByVal alwaysPaysOnTime As Boolean)
- Me.AlwaysPaysOnTime = alwaysPaysOnTime
- End Sub
-
- ' We don't charge shipment to well-behaved foreign customers.
- Protected Overrides Function ShipmentDiscount() As Single
- If AlwaysPaysOnTime Then ShipmentDiscount = 100
- End Function
- End Class
-
- ' the DataReader and FileDateReader classes demonstrate the simplest technique
- ' for a derived class to trap events from a base class
-
- Class DataReader
- Event DataAvailable()
-
- Sub GetNewData()
- RaiseEvent DataAvailable()
- End Sub
- End Class
-
- Class FileDataReader
- Inherits DataReader
-
- ' This variable will point to the object itself (Me).
- Dim WithEvents EventSink As FileDataReader
- ' This counter must be incremented after each event.
- Public EventCounter As Integer
-
- Sub New()
- MyBase.New()
- EventSink = Me
- End Sub
-
- Private Sub NotifyDataAvailable() Handles EventSink.DataAvailable
- ' Increment the counter.
- EventCounter += 1
- End Sub
- End Class
-
- ' The DataReader2 and FileDataReader2 classes demonstrate a more sophisticated technique
- ' for a derived class to control events fired in its base class
-
- Class DataReader2
- Event DataAvailable()
-
- Sub GetNewData()
- OnDataAvailable()
- End Sub
-
- Protected Overridable Sub OnDataAvailable()
- RaiseEvent DataAvailable()
- End Sub
- End Class
-
- Class FileDataReader2
- Inherits DataReader2
-
- ' This counter must be incremented after each event.
- Public EventCounter As Integer
-
- Protected Overrides Sub OnDataAvailable()
- ' Increment the counter.
- EventCounter += 1
- ' Raise only up to 10 events.
- If EventCounter <= 10 Then MyBase.OnDataAvailable()
- End Sub
- End Class
-
- ' these classes are used to test member shadowing
-
- Class AAA
- Sub DoSomething()
- Console.WriteLine("AAA.DoSomething")
- End Sub
- Sub DoSomething(ByVal msg As String)
- Console.WriteLine("AAA.DoSomething({0})", msg)
- End Sub
-
- Sub DoSomething2()
- Console.WriteLine("AAA.DoSomething2")
- End Sub
- Sub DoSomething2(ByVal msg As String)
- Console.WriteLine("AAA.DoSomething2({0})", msg)
- End Sub
-
- End Class
-
- Class BBB
- Inherits AAA
-
- Overloads Sub DoSomething()
- Console.WriteLine("BBB.DoSomething")
- End Sub
-
- Private Shadows Sub DoSomething2()
- Console.WriteLine("BBB.DoSomething2")
- End Sub
-
- End Class
-
-